package com.hxkcloud.nurse.activitys;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.UrlAddress;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.BrightnessUtils;

import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by william_sun on 2016-08-10.
 * Description:webview的文章详情
 */
public class ArticleDetailActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout ll_root;
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_collect;
    private View views;
    private WebView webView;
    private ProgressBar pb_web;

    private String articleId;
    private String acctType = YjhApplication.articlekind_course;//0资讯 1课堂文章
    private String name;
    // [170514] 要跳转的评论
    private String commentId;

    private String kindTitle;

    private String isFromCollection="";

//    private TextView tv_test ;
    private PopupWindow show_replay;
    private Button btn_send;
    private EditText et_message;
    private String url;
    private String articleInfoId;
    private String userId;
    private String kindName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articledetail);

        articleId = getIntent().getStringExtra("articleId");
        acctType = getIntent().getStringExtra("acctType");
        name = getIntent().getStringExtra("name");
        commentId = getIntent().getStringExtra("commentId");

        kindTitle = getIntent().getStringExtra("kindTitle");
        if (getIntent().hasExtra("kindName")){
            if (!TextUtils.isEmpty(getIntent().getStringExtra("kindName"))){
                kindTitle = getIntent().getStringExtra("kindName");
            }
        }
//        if (getIntent().hasExtra("type")){
//            acctType = getIntent().getStringExtra("type");
//        }
        if(getIntent().hasExtra("isFromCollection")){
            isFromCollection = getIntent().getStringExtra("isFromCollection");
        }
        initView();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_COLLECTARTICALINFO_SUCCESS:
                if (msg.obj != null) {
//                    if(msg.obj.toString().equals(R.string.already_collect_success)){
//                        toastMsg(msg.obj.toString());
//                    }else{
//                        toastMsg(R.string.collect_success);
//                    }
                    toastMsg(msg.obj.toString());

                } else {
                    toastMsg(R.string.collect_success);
                }
                break;
            case MessageCode.NETWORKCODE_COLLECTARTICALINFO_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.collect_fail);
                }
                break;
            //评论成功
            case MessageCode.NETWORKCODE_NUSERARTICALINFO_SUCCESS:
                toastMsg("评论成功");
                show_replay.dismiss();
                et_message.setText("");
                webView.loadUrl(url);

                break;
            case MessageCode.NETWORKCODE_NUSERARTICALINFO_FAILURE:
                toastMsg("评论失败");
                break;
        }
    }

    @Override
    protected void initView() {
        ll_root = (LinearLayout) findViewById(R.id.ll_roots);
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_collect = (TextView) findViewById(R.id.tv_title_func);

        views = LayoutInflater.from(mContext).inflate(R.layout.activity_layout_comment,null);
        btn_send = (Button) views.findViewById(R.id.comment_btn_submit);
        et_message = (EditText) views.findViewById(R.id.et_comment);
//        tv_test = (TextView) findViewById(R.id.textView_test);
//        tv_test.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//               showpopwind();
//            }
//        });

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(kindTitle);
        tv_collect.setVisibility(View.VISIBLE);
        if("true".equals(isFromCollection)){
            tv_collect.setText(getResources().getText(R.string.cancel_collect));
        }else{
            tv_collect.setText(getResources().getText(R.string.newsdetail_text_collect));
        }

        tv_collect.setOnClickListener(this);

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
            tv_collect.setVisibility(View.INVISIBLE);
        }

        webView = (WebView) findViewById(R.id.webview_article);
        pb_web = (ProgressBar) findViewById(R.id.pb_article);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true); //支持js
        webSettings.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSettings.setSupportZoom(true);  //支持缩放
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置缓存模式
        webSettings.setDomStorageEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("comment_article")) {
                    String[] addNum = url.split("=");
                    String pattentId = splitNum(addNum[2]);
                    String faulteId = splitNum(addNum[3]);
                    String[] userIds = addNum[4].split("&");
                    String userIddecode = userIds[0];
                    articleInfoId = addNum[5];
                    try {
                        //userId = new String(userIddecode.getBytes("iso-8859-1"), "UTF-8");
                        userId = URLDecoder.decode(userIddecode,"UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if(!TextUtils.isEmpty(userId)){
                        SpannableString s = new SpannableString("回复"+userId+":");
                        et_message.setHint(s);
                    }
                    BrightnessUtils.lightOff(ArticleDetailActivity.this);
                    showpopwind(pattentId,faulteId);
                   // toastMsg("进入点击事件");
//                    Intent iComment = new Intent(mContext, CommentActivity.class);
//                    iComment.putExtra("articleId", articleId);
//                    iComment.putExtra("acctType", acctType);
//                    startActivity(iComment);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb_web.setProgress(newProgress);
                if (newProgress == 100) {
                    pb_web.setVisibility(View.INVISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        url = UrlAddress.H5_ARTICLEINFO_URL + "&articleId=" + articleId + "&acctType=" + loginInfo.getUserStyle() + "&userId=" + loginInfo.getUserId()+"&flag=app";
        if (commentId != null)
        {
            url = url + "&pid=" + commentId;
        }
        webView.loadUrl(url);
    }

    private String decode(String unicodeStr) {
            if (unicodeStr == null) {
                return null;
            }
            StringBuffer retBuf = new StringBuffer();
            int maxLoop = unicodeStr.length();
            for (int i = 0; i < maxLoop; i++) {
                if (unicodeStr.charAt(i) == '\\') {
                    if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
                        try {
                            retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                            i += 5;
                        } catch (NumberFormatException localNumberFormatException) {
                            retBuf.append(unicodeStr.charAt(i));
                        }
                    else
                        retBuf.append(unicodeStr.charAt(i));
                } else {
                    retBuf.append(unicodeStr.charAt(i));
                }
            }
            return retBuf.toString();

    }

    private String splitNum(String s) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(s);
        String num=m.replaceAll("").trim().toString();
        if (TextUtils.isEmpty(num)){
            return "";
        }else {
            return num;
        }

    }

    private void showpopwind(final String patendId, final String faulter) {

        View view_back = views.findViewById(R.id.view_back);
        view_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show_replay.dismiss();
            }
        });
        InputFilter[] emojiFilters = {emojiFilter};
        et_message.setFilters(new InputFilter[]{emojiFilter});
        et_message.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!TextUtils.isEmpty(et_message.getText().toString().trim())){
                    btn_send.setTextColor(getResources().getColor(R.color.greenLight));
                }else {
                    btn_send.setTextColor(getResources().getColor(R.color.grey_text2));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(et_message.getText().toString().trim())){
                    String message = et_message.getText().toString();
                    YiJiaHuNetWorkUtils.ArticalDetail(loginInfo.getUserId(),faulter,message,patendId,articleInfoId,handler);
                }else {
                    toastMsg("请输入回复信息!");
                }
            }
        });
        et_message.setFocusable(true);
        et_message.setFocusableInTouchMode(true);
        et_message.requestFocus();
        et_message.requestFocusFromTouch();
        openKeyboard();
        show_replay = new PopupWindow(views, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        show_replay.setFocusable(true);
        show_replay.setBackgroundDrawable(new BitmapDrawable());
        show_replay.setOutsideTouchable(true);
        show_replay.setTouchable(true);
        show_replay.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        show_replay.setAnimationStyle(R.style.popupwindow_anim_default);
        show_replay.showAtLocation(ll_root,Gravity.BOTTOM,0,0);
        show_replay.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(ArticleDetailActivity.this);
            }
        });
    }

    InputFilter emojiFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                toastMsg("不支持输入表情");
                return "";
            }
            return null;
        }
    };
    private void openKeyboard() {
        InputMethodManager imm = (InputMethodManager)ArticleDetailActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        webView.loadData("<a></a>", "text/html", "utf-8");
        super.onPause();
    }


        @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.tv_title_func:
                loading();
                //收藏    0收藏1取消收藏
                if("true".equals(isFromCollection)){
                    YiJiaHuNetWorkUtils.collectArtical(articleId, "1", acctType + "", handler);
                }else{
                    YiJiaHuNetWorkUtils.collectArtical(articleId, "0", acctType + "", handler);
                }
                break;
        }
    }
}
